package com.ruoyi.manage.enterprise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.celoan.service.ExTradeEffectFinancingrequirementsDetailService;
import com.ruoyi.common.constant.CodeConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ListUtil;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.NumsUtils;
import com.ruoyi.manage.enterprise.domain.*;
import com.ruoyi.manage.enterprise.domain.vo.EcEnterpriseFinancingInfoVo;
import com.ruoyi.manage.enterprise.mapper.EcEnterpriseFinancingInfoMapper;
import com.ruoyi.manage.enterprise.service.*;
import com.ruoyi.manage.organization.domain.OcFinancingMatch;
import com.ruoyi.manage.organization.service.IOcFinancingMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;


/**
 * 企业融资需求Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-13
 */
@Service
public class EcEnterpriseFinancingInfoServiceImpl extends ServiceImpl<EcEnterpriseFinancingInfoMapper, EcEnterpriseFinancingInfo> implements IEcEnterpriseFinancingInfoService {

    @Autowired
    IEcEnterpriseInformationService iEcEnterpriseInformationService;

    @Autowired
    IEcEnterpriseLegalService iEcEnterpriseLegalService;

    @Autowired
    IPcProductBaseInfoService iPcProductBaseInfoService;

    @Autowired
    IEcEnterpriseContactService iEcEnterpriseContactService;

    @Autowired
    IOcFinancingMatchService iOcFinancingMatchService;

    @Autowired
    IPcProductExtendInfoService iPcProductExtendInfoService;

    @Autowired
    ExTradeEffectFinancingrequirementsDetailService effectFinancingrequirementsDetailService;

    @Override
    public EcEnterpriseFinancingInfoVo queryGetById(Long id) {
        EcEnterpriseFinancingInfoVo financingInfoVo = new EcEnterpriseFinancingInfoVo();
        EcEnterpriseFinancingInfo FinancingInfo = this.getById(id);
        BeanUtils.copyProperties(FinancingInfo, financingInfoVo);
//       查询企业信息
        EcEnterpriseInformation ecEnterpriseInformation = iEcEnterpriseInformationService.queryGetById(FinancingInfo.getEnterpriseId());
        financingInfoVo.setInformation(ecEnterpriseInformation);

//        查询企业法人
        EcEnterpriseLegal legalPerson = iEcEnterpriseLegalService.getOne(new QueryWrapper<EcEnterpriseLegal>().eq("enterprise_id", FinancingInfo.getEnterpriseId()));
        financingInfoVo.setLegal(legalPerson);
        return financingInfoVo;
    }

    /**
     * 新增企业融资需求
     *
     * @param ecEnterpriseFinancingInfo 企业融资需求
     * @return 结果
     */
    @Override
    public boolean addEcEnterpriseFinancingInfo(EcEnterpriseFinancingInfo ecEnterpriseFinancingInfo) {
        boolean save = this.save(ecEnterpriseFinancingInfo);
        return save;
    }

    @Override
    @Transactional
    public boolean addEcEnterpriseFinancingInfoMore(EcEnterpriseFinancingInfoVo ecEnterpriseFinancingInfoVo) {


//        新增融资需求需求表
        ecEnterpriseFinancingInfoVo.setApplyNo(NumsUtils.generateCode(CodeConstants.APPLY_DEMAND));
        ecEnterpriseFinancingInfoVo.setApplyWay("0");
        ecEnterpriseFinancingInfoVo.setApplyState("1");
        boolean save = this.save(ecEnterpriseFinancingInfoVo);

//        更新企业信息
        EcEnterpriseInformation information = ecEnterpriseFinancingInfoVo.getInformation();
        boolean enterInfo = iEcEnterpriseInformationService.updateById(information);
        if (!enterInfo) {
            throw new CustomException("保存失败");
        }

//      更新法人信息
        boolean legalSave = iEcEnterpriseLegalService.updateById(ecEnterpriseFinancingInfoVo.getLegal());
        if (!legalSave) {
            throw new CustomException("保存失败");
        }


//        增加融资需求匹配表
        if (ObjUtil.isNotNull(ecEnterpriseFinancingInfoVo.getProductId())) {
            addFinancingMatch(ecEnterpriseFinancingInfoVo);
            return true;
        }

//      自动分配融资需求


//      增加融资需求上报信息
//        ThreadUtil.execAsync(() -> effectFinancingrequirementsDetailService.addFinancingrequirementsDetail(ecEnterpriseFinancingInfoVo));
        return save;
    }

    public void autoMatchProduct(EcEnterpriseFinancingInfo ecEnterpriseFinancingInfo){

//            iPcProductBaseInfoService.lambdaQuery().and(a->a.ge(PcProductBaseInfo::getAmountLimitLower,ecEnterpriseFinancingInfo.getApplyAmountMin())).
//                    .le(PcProductBaseInfo::getAmountLimitUpper,ecEnterpriseFinancingInfo.getApplyAmountMax())

    }

    /**
     * 增加产品匹配表
     */
    public void addFinancingMatch(EcEnterpriseFinancingInfoVo ecEnterpriseFinancing) {
//        获取产品信息
        PcProductBaseInfo productBaseInfo = iPcProductBaseInfoService.getById(ecEnterpriseFinancing.getProductId());
        PcProductExtendInfo productExtendInfo = iPcProductExtendInfoService.getOne(new QueryWrapper<PcProductExtendInfo>().eq("product_id", ecEnterpriseFinancing.getProductId()));
        if (ObjUtil.isNull(productBaseInfo)) {
            throw new CustomException("产品不存在");
        }
        //      增加需求产品匹配

        OcFinancingMatch financingMatch = OcFinancingMatch.builder()
//                插入企业信息
                .enterpriseId(ecEnterpriseFinancing.getEnterpriseId())
                .enterpriseName(ecEnterpriseFinancing.getEnterpriseName())
                .applyId(ecEnterpriseFinancing.getApplyNo())
                .creditCode(ecEnterpriseFinancing.getInformation().getCreditCode())
                .areaName(ecEnterpriseFinancing.getAreaName())
                .areaSiteId(ecEnterpriseFinancing.getAreaSiteId())
                .cityName(ecEnterpriseFinancing.getCityName())
                .citySiteId(ecEnterpriseFinancing.getCitySiteId())
                .provinceName(ecEnterpriseFinancing.getProvinceName())
                .provinceSiteId(ecEnterpriseFinancing.getProvinceSiteId())
//                插入融资信息
                .matchType("2")
                .matchState("0")
                .applyAmountMin(ecEnterpriseFinancing.getApplyAmountMin())
                .applyAmountMax(ecEnterpriseFinancing.getApplyAmountMax())
                .arrivalTimeType(ecEnterpriseFinancing.getArrivalTimeType())
                .maturityMax(ecEnterpriseFinancing.getMaturityMax())
                .maturityMin(ecEnterpriseFinancing.getMaturityMin())
                .rateMax(ecEnterpriseFinancing.getRateMax())
                .rateMin(ecEnterpriseFinancing.getRateMin())
                .taxLevel(ecEnterpriseFinancing.getTaxLevel())
                .depositBank(ecEnterpriseFinancing.getInformation().getDepositBank())
                .taxAmount(ecEnterpriseFinancing.getTaxAmount())
                .incomeData(ecEnterpriseFinancing.getIncomeData())
                .profitState(ecEnterpriseFinancing.getProfitState())
                .collateralFlag(ecEnterpriseFinancing.getCollateralFlag())
                .loanBankName(ecEnterpriseFinancing.getLoanBankName())
                .loanLeftAmount(ecEnterpriseFinancing.getLoanLeftAmount())
                .guaranteeType(ecEnterpriseFinancing.getGuaranteeType())
                .repaymentType(ecEnterpriseFinancing.getRepaymentType())
//                插入产品信息
                .productId(productBaseInfo.getId())
                .productName(productBaseInfo.getProductName())
                .amountLimitLower(productBaseInfo.getAmountLimitLower())
                .amountLimitUpper(productBaseInfo.getAmountLimitUpper())
                .interestRateLimitLower(productBaseInfo.getInterestRateLimitLower())
                .interestRateLimitUpper(productBaseInfo.getInterestRateLimitUpper())
                .loanPeriodLimitLower(productBaseInfo.getLoanPeriodLimitLower())
                .loanPeriodLimitUpper(productBaseInfo.getLoanPeriodLimitUpper())
                .mainGuaranteeWay(productBaseInfo.getMainGuaranteeWay())
                .secondGuaranteeWay(productBaseInfo.getSecondGuaranteeWay())
                .productFeature(productExtendInfo.getProductFeature())
                .repaymentWay(productBaseInfo.getRepaymentWay())
                .productLogo(productBaseInfo.getProductLogo())
                .orgPath(productBaseInfo.getBelongInstitution())
                .coveragePath(productBaseInfo.getCoverage())
                .applyTime(new Date())
                .build();
        boolean saveMatch = iOcFinancingMatchService.addOcFinancingMatch(financingMatch);
        if (!saveMatch) {
            throw new CustomException("产品申请失败");
        }
    }

    /**
     * 修改企业融资需求
     *
     * @param ecEnterpriseFinancingInfo 企业融资需求
     * @return 结果
     */
    @Override
    public boolean updateEcEnterpriseFinancingInfo(EcEnterpriseFinancingInfo ecEnterpriseFinancingInfo) {
        return this.updateById(ecEnterpriseFinancingInfo);
    }

    /**
     * 批量删除企业融资需求
     *
     * @param ids 需要删除的企业融资需求主键
     * @return 结果
     */
    @Override
    public boolean deleteEcEnterpriseFinancingInfoByIds(Long[] ids) {
        return this.removeByIds(ListUtil.toList(ids));
    }

    /**
     * 查询企业融资需求信息表
     */
    @Override
    public List<EcEnterpriseFinancingInfoVo> selectDemandEnterpriseTable() {

        return Collections.emptyList();
    }

    @Override
    public List<EcEnterpriseFinancingInfo> selectFinanceInfoService(Long enterpriseId) {
        return baseMapper.selectFinanceInfo(enterpriseId);
    }

}
